package com.example.administrator.newxlmedical;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import org.w3c.dom.Text;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import adapters.CountSpinnerAdapter;
import adapters.RemindListViewAdapter;
import beans.CabinetInfoBean;
import beans.GoodsDetailInfoBean;
import beans.GoodsDetailsBean;
import beans.GoodsInfoBean;
import beans.TimeoutBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import dialogs.DateDialog;
import dialogs.GoodsDetialsDialog;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.FormateUtils;
import utils.ObjectSaveUtil;
import utils.TimeOutSortUtils;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.ViewUtil;

public class TimeOutActivity extends BaseActivity {

    @BindView(R.id.btn_time_out_search)
    Button btnSearch;
    @BindView(R.id.fl_time_out)
    FrameLayout flEmpty;
    @BindView(R.id.remind_goods)
    TextView tvGoods;
    @BindView(R.id.iv_timeout_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_timeout_goods_sort)
    RelativeLayout rlGoodsSort;
    @BindView(R.id.remind_supplier)
    TextView tvSupplier;
    @BindView(R.id.iv_timeout_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_timeout_supplier_sort)
    RelativeLayout rlSupplierSort;
    @BindView(R.id.remind_data_end)
    TextView tvTime;
    @BindView(R.id.iv_timeout_time_sort)
    ImageView ivTimeSort;
    @BindView(R.id.rl_timeout_time_sort)
    RelativeLayout rlTimeSort;
    @BindView(R.id.remind_number)
    TextView tvCabinet;
    @BindView(R.id.iv_timeout_cabinet_sort)
    ImageView ivCabinetSort;
    @BindView(R.id.rl_timeout_cabinet_sort)
    RelativeLayout rlCabinetSort;
    @BindView(R.id.remind_size)
    TextView tvSpecification;
    @BindView(R.id.iv_timeout_specification_sort)
    ImageView ivSpecificationSort;
    @BindView(R.id.rl_timeout_specification_sort)
    RelativeLayout rlSpecificationSort;
    @BindView(R.id.remind_count)
    TextView tvNumber;
    @BindView(R.id.iv_timeout_number_sort)
    ImageView ivNumberSort;
    @BindView(R.id.rl_timeout_number_sort)
    RelativeLayout rlNumberSort;

    private ImageView mIv_home;
    private String[] spinnerData = {"全部", "1", "2", "3", "4", "5"};
    private CountSpinnerAdapter mAdapter;
    private Spinner mSpinner;
    private ListView mListView;
    private TextView mStartData;
    private TextView mEndData;
    private RemindListViewAdapter lvAdapter;
    public Map<Integer, String> hashMap = new HashMap<>();
    private StringBuffer sb = new StringBuffer();
    private RelativeLayout mRl_empty;
    private LinearLayout mLl_empty;
    private int type;
    private int mPosition = 0;
    private List<TimeoutBean> list = new ArrayList<>();
    private List<TimeoutBean> normalList = new ArrayList<>();
    private List<TimeoutBean> cabinetList = new ArrayList<>();
    private boolean isSearchToCabinet = false;
    private boolean isSortGoods, isSortCabinet, isSortSpecification, isSortSupplier, isSortNumber, isSortTimeOut;
    private int sortGoods, sortCabinet, sortSpecification, sortSupplier, sortNumber, sortTimeOut;
    private MyHandler allHandler = SingletonClass.getSingleton(MyHandler.class);
    private boolean isFrist = true;
    private int cabinetNUmber ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_out);
        ButterKnife.bind(this);
    }

    @Override
    public void initView() {

        Map<String, Integer> readMap = (Map<String, Integer>) ObjectSaveUtil.readObject(this, Constants.CABINET_NUMBER, Constants.CABINET_NUMBER);
        if (readMap != null && readMap.size() != 0) {
            spinnerData = new String[readMap.size() + 1];
            Set setMap = readMap.entrySet();
            Iterator mapInterator = setMap.iterator();
            List<Integer> cabinetList = new ArrayList<>();
            while (mapInterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) mapInterator.next();
                int number = (int) mapentry.getValue();
                cabinetList.add(number);
            }
            Collections.sort(cabinetList);
            spinnerData[0] = "全部";
            for (int i = 0; i < cabinetList.size(); i++) {
                spinnerData[i + 1] = cabinetList.get(i)+"";
            }
        } else {
            spinnerData = new String[]{"全部"};
        }

        mIv_home = (ImageView) findViewById(R.id.remind_home);
        mSpinner = (Spinner) findViewById(R.id.remind_spinner);

        mListView = (ListView) findViewById(R.id.remind_lv);
        lvAdapter = new RemindListViewAdapter(TimeOutActivity.this, list, R.layout.remind_list);
        mListView.setAdapter(lvAdapter);
        mListView.setVisibility(View.GONE);

//        initTime();
        Object o = ObjectSaveUtil.readObject(this, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);

        sb.delete(0, sb.length());
        if (o != null) {
            hashMap = (Map<Integer, String>) o;
            Set set = hashMap.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Map.Entry mapentry = (Map.Entry) iterator.next();
                sb.append("'" + mapentry.getKey() + "',");
            }
            sb.deleteCharAt(sb.length() - 1);
            Log.e(TAG, "sb = " + sb.toString());
        }

        loadingTask();
    }

    @Override
    protected void setListener() {
        super.setListener();
        mIv_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtil.jumpToActivity(TimeOutActivity.this, MainActivity.class);
                finish();
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TimeoutBean bean = list.get(position);

                GoodsDetailInfoBean infoBean = new GoodsDetailInfoBean();
                infoBean.setName(bean.getName());
                infoBean.setBarCode(bean.getBarCode());
                infoBean.setSpecification(bean.getSpecification());
                infoBean.setSupplier(bean.getManufactor());
                infoBean.setTime(bean.getTimeoutDate());
                infoBean.setUnit(bean.getUnit());
                infoBean.setNumber(bean.getNumber());
                infoBean.setStatus(Integer.parseInt(bean.getStatus()));
                infoBean.setTimeName("过期时间 : ");
                infoBean.setTitle("近校提醒");
                infoBean.setTitleContent("物品详情");

                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.GOODS_DETIAL_INFO,infoBean);
                Intent intent = new Intent(TimeOutActivity.this, GoodsDetialActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });

        mAdapter = new CountSpinnerAdapter(this, R.layout.time_out_spinner_layout, spinnerData);

        mAdapter.setDropDownViewResource(R.layout.spinner_bg);

        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                ToastUtil.showToast(TimeOutActivity.this,position+"");
                mPosition = position;
                mAdapter.setSelectPosition(mPosition);
                if (position != 0) {
                    cabinetNUmber = Integer.parseInt(spinnerData[position]);
                }else {
                    cabinetNUmber = 0;
                }

                if (!isFrist) {
                    btnSearch.setClickable(false);
                    mListView.setVisibility(View.GONE);
                    list.clear();
                    normalList.clear();
                    loadingTask();
                }else {
                    isFrist = false;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mSpinner.setAdapter(mAdapter);

    }

    public void loadingTask() {
        Log.e(TAG, "loadingTask: " );
        sort(0);
        hideEmptyView();
        showLoadingView(flEmpty);

        String sql = "select * from GoodsDetails where CabinetInfoId in (" + sb.toString() + ") and DATEADD(dd,-90,LastTime) < getdate() and Status = 3";

        Call<ArrayList<GoodsDetailsBean>> call = GetRetrofit.getInstance().getGoodsDetailsPage(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<ArrayList<GoodsDetailsBean>>() {
            @Override
            public void onResponse(Call<ArrayList<GoodsDetailsBean>> call, Response<ArrayList<GoodsDetailsBean>> response) {
                ArrayList<GoodsDetailsBean> body = response.body();
                if (body != null && body.size() > 0) {
                    //为了将到期时间相同,goodsInfoId相同的物品显示为一条,所做的数据处理
                    StringBuilder stringBuilder = new StringBuilder();
                    Map<String, TimeoutBean> map = new HashMap();
                    int size = body.size();
                    GoodsDetailsBean goodsDetailsBean;
                    for (int i = 0; i < size; i++) {
                        goodsDetailsBean = body.get(i);
                        TimeoutBean timeoutBean = new TimeoutBean();
                        timeoutBean.setCabinetInfoId(goodsDetailsBean.getCabinetInfoId());
                        timeoutBean.setGoodsInfoId(goodsDetailsBean.getGoodsInfoId());
                        timeoutBean.setTimeoutDate(goodsDetailsBean.getLastTime().substring(0, 10));
                        timeoutBean.setDataTime(goodsDetailsBean.getLastTime());
                        timeoutBean.setStatus(goodsDetailsBean.getStatus() + "");
                        String key = timeoutBean.getTimeoutDate() + timeoutBean.getGoodsInfoId() + timeoutBean.getCabinetInfoId();
                        if (map.get(key) != null) {
                            TimeoutBean bean = map.get(key);
                            timeoutBean.setNumber(bean.getNumber() + 1);
                            timeoutBean.getBarCode().addAll(bean.getBarCode());
                        }
                        // 为详情页面做准备
                        String time;
                        if (TextUtils.isEmpty(goodsDetailsBean.getReturnTime())){
                            if (!TextUtils.isEmpty(goodsDetailsBean.getIntoCabinetTime())) {
                                time = TimeUtil.getNowTime(goodsDetailsBean.getIntoCabinetTime()).substring(0, 19);
                            }else {
                                time = TimeUtil.getMillisecondDate().substring(0,TimeUtil.getMillisecondDate().length() - 4);
                            }
                        }else {
                            time = TimeUtil.getNowTime(goodsDetailsBean.getReturnTime()).substring(0,19);
                        }
                        timeoutBean.getBarCode().add(goodsDetailsBean.getBarCode() + Constants.INCREASE_DECREASE_SPLIT + time);
                        map.put(key, timeoutBean);
                    }
                    Set set = map.entrySet();
                    Iterator iterator = set.iterator();
                    while (iterator.hasNext()) {
                        Map.Entry mapentry = (Map.Entry) iterator.next();
                        TimeoutBean bean = (TimeoutBean) mapentry.getValue();
                        stringBuilder.append("'" + bean.getGoodsInfoId() + "',");
                        list.add(bean);
                        normalList.add(bean);
                    }
                    Log.e(TAG, "list: " + list.size());
                    if (stringBuilder.length() > 0) {
                        String goodsInfoIds = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                        getGoodsInfo(goodsInfoIds);

                    } else {
                        btnSearch.setClickable(true);
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }

                } else {
                    btnSearch.setClickable(true);
                    hideLoadingView();
                    if (list.size() == 0) {
                        showEmptyView(flEmpty);
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrayList<GoodsDetailsBean>> call, Throwable t) {
                ToastUtil.showToast(TimeOutActivity.this, "失败");
                hideLoadingView();
                showEmptyView(flEmpty);
                btnSearch.setClickable(true);
            }
        });
    }

    private void getGoodsInfo(String goodsInfoIds) {
        Call<ArrayList<GoodsInfoBean>> call = GetRetrofit.getInstance().getGoodsInfo(NetAddress.token, NetAddress.machineCode, "select * from GoodsInfo where ID in (" + goodsInfoIds + ")");
        call.enqueue(new Callback<ArrayList<GoodsInfoBean>>() {
            @Override
            public void onResponse(Call<ArrayList<GoodsInfoBean>> call, Response<ArrayList<GoodsInfoBean>> response) {
                hideLoadingView();
                ArrayList<GoodsInfoBean> body = response.body();
                if (body != null && body.size() != 0) {
                    Log.e(TAG, "body: " + body.size());
                    for (int i = 0; i < list.size(); i++) {
                        TimeoutBean timeoutBean = list.get(i);
                        for (int m = 0; m < body.size(); m++) {
                            GoodsInfoBean goodsInfoBean = body.get(m);
                            if (goodsInfoBean.getID() == timeoutBean.getGoodsInfoId()) {
                                //填充logFragmentBean所需要的数据
                                timeoutBean.setGoodsUnit(goodsInfoBean.getGoodsUnit());
                                timeoutBean.setName(goodsInfoBean.getGoodName());
                                timeoutBean.setSpecification(goodsInfoBean.getSpecification());
                                timeoutBean.setManufactor(goodsInfoBean.getManufacturer());
                                timeoutBean.setUnit(goodsInfoBean.getGoodsUnit());
//                            timeoutBean.setVersion(goodsInfoBean.getVersion());
                                break;
                            }
                        }
                    }
                    getCabinetInfoId();
                } else {
                    btnSearch.setClickable(true);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<GoodsInfoBean>> call, Throwable t) {
                hideLoadingView();
                showEmptyView(flEmpty);
                btnSearch.setClickable(true);
            }
        });
    }

    public void getCabinetInfoId() {
        String sql = "select * from CabinetInfo where TerminalInfoID = " + NetAddress.terminalInfoId;
        GetRetrofit.getInstance().getCabinetInfoId1(NetAddress.token, NetAddress.machineCode, sql)
                .enqueue(new Callback<ArrayList<CabinetInfoBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<CabinetInfoBean>> call, Response<ArrayList<CabinetInfoBean>> response) {
                        ArrayList<CabinetInfoBean> body = response.body();
                        if (body != null && body.size() > 0) {
                            for (int i = 0; i < list.size(); i++) {
                                TimeoutBean bean = list.get(i);
                                for (int j = 0; j < body.size(); j++) {
                                    CabinetInfoBean cabinetInfoBean = body.get(j);
                                    if (bean.getCabinetInfoId() == cabinetInfoBean.getID()) {
                                        list.get(i).setCabinetCode(cabinetInfoBean.getLogicNumber());
                                    }
                                }
                            }
                            if (cabinetNUmber == 0) {
                                mListView.setVisibility(View.VISIBLE);
                                lvAdapter.notifyDataSetChanged();
                            } else {
                                searchToCabinet();
                            }
                        } else {
                            sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                        }
                        btnSearch.setClickable(true);
                    }

                    @Override
                    public void onFailure(Call<ArrayList<CabinetInfoBean>> call, Throwable t) {
                        btnSearch.setClickable(true);
                    }
                });
    }

    private void searchToCabinet() {
        normalList.clear();
        ArrayList<TimeoutBean> arrayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            TimeoutBean timeoutBean = list.get(i);
            if (Integer.parseInt(timeoutBean.getCabinetCode()) == cabinetNUmber) {
                arrayList.add(timeoutBean);
            }
        }
        if (arrayList.size() > 0) {
            normalList.addAll(arrayList);
            mListView.setVisibility(View.VISIBLE);
            list.clear();
            list.addAll(normalList);
            lvAdapter.notifyDataSetChanged();
        } else {
            mListView.setVisibility(View.GONE);
            showEmptyView(flEmpty);
        }
    }

    private void initTime() {
        mStartData = (TextView) findViewById(R.id.remind_time_start);
        mEndData = (TextView) findViewById(R.id.remind_time_end);
        String nowTime = TimeUtil.getMillisecondDate();
        mStartData.setText(nowTime.substring(0, 10));
        mEndData.setText(nowTime.substring(0, 10));

        if (String.valueOf(TimeUtil.getDay()).length() < 2) {
            mStartData.setText(TimeUtil.getYear() + "-" + FormateUtils.appendZero(TimeUtil.getMonth() + 1) + "-0" + TimeUtil.getDay());
        } else {
            mStartData.setText(TimeUtil.getYear() + "-" + FormateUtils.appendZero(TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay());
        }

        //12月,下個月是1月
        if (TimeUtil.getMonth() == 11) {
            if (String.valueOf(TimeUtil.getDay()).length() < 2) {
                mEndData.setText((TimeUtil.getYear() + 1) + "-01-0" + TimeUtil.getDay());
            } else {
                mEndData.setText((TimeUtil.getYear() + 1) + "-01-" + TimeUtil.getDay());
            }
        } else {
            if (String.valueOf(TimeUtil.getDay()).length() < 2) {
                mEndData.setText(TimeUtil.getYear() + "-" + FormateUtils.appendZero(TimeUtil.getMonth() + 4) + "-0" + TimeUtil.getDay());
            } else {
                mEndData.setText(TimeUtil.getYear() + "-" + FormateUtils.appendZero(TimeUtil.getMonth() + 4) + "-" + TimeUtil.getDay());
            }
        }
    }

    @OnClick({R.id.btn_time_out_search, R.id.rl_timeout_goods_sort, R.id.rl_timeout_supplier_sort, R.id.rl_timeout_time_sort,
            R.id.rl_timeout_cabinet_sort, R.id.rl_timeout_specification_sort, R.id.rl_timeout_number_sort})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.btn_time_out_search:

                break;

            case R.id.rl_timeout_goods_sort:
                sort(1);
                break;

            case R.id.rl_timeout_supplier_sort:
                sort(2);
                break;

            case R.id.rl_timeout_time_sort:
                sort(3);
                break;

            case R.id.rl_timeout_cabinet_sort:
                sort(4);
                break;

            case R.id.rl_timeout_specification_sort:
                sort(5);
                break;

            case R.id.rl_timeout_number_sort:
                sort(6);
                break;
        }

    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                TimeOutSortUtils.sortTimeOutGoods(list, isSortGoods);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(normalList);
            }

        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                isSortSupplier = !isSortSupplier;
                sortSupplier++;
                TimeOutSortUtils.sortTimeOutSupplier(list, isSortSupplier);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(normalList);
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {  // 按时间排序
            if (sortTimeOut != 2) {
                isSortTimeOut = !isSortTimeOut;
                sortTimeOut++;
                TimeOutSortUtils.sortTimeOut(list, isSortTimeOut);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(normalList);
            }
        } else {
            sortTimeOut = 0;
            isSortTimeOut = false;
        }

        if (type == 4) { // 柜号
            if (sortCabinet != 2) {
                isSortCabinet = !isSortCabinet;
                sortCabinet++;
                TimeOutSortUtils.sortTimeOutCabinet(list, isSortCabinet);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(normalList);
            }
        } else {
            sortCabinet = 0;
            isSortCabinet = false;
        }

        if (type == 5) { // 规格
            if (sortSpecification != 2) {
                isSortSpecification = !isSortSpecification;
                sortSpecification++;
                TimeOutSortUtils.sortTimeOutSpecification(list, isSortSpecification);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(normalList);
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        if (type == 6) {  // 数量
            if (sortNumber != 2) {
                isSortNumber = !isSortNumber;
                sortNumber++;
                TimeOutSortUtils.sortTimeOutNumber(list, isSortNumber);
            } else {
                clearSortDate();
                list.clear();
                list.addAll(normalList);
            }
        } else {
            sortNumber = 0;
            isSortNumber = false;
        }

        ViewUtil.setSortColor(this, tvGoods, ivGoodsSort, sortGoods);
        ViewUtil.setSortColor(this, tvSupplier, ivSupplierSort, sortSupplier);
        ViewUtil.setSortColor(this, tvTime, ivTimeSort, sortTimeOut);
        ViewUtil.setSortColor(this, tvCabinet, ivCabinetSort, sortCabinet);
        ViewUtil.setSortColor(this, tvSpecification, ivSpecificationSort, sortSpecification);
        ViewUtil.setSortColor(this, tvNumber, ivNumberSort, sortNumber);

        lvAdapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        sortGoods = 0;
        sortSupplier = 0;
        sortTimeOut = 0;
        sortCabinet = 0;
        sortSpecification = 0;
        sortNumber = 0;
    }

}
